package com.sz.ac.services.ac;

import com.sz.ac.entity.AcBallLog;
import com.sz.ac.entity.AcGrp;
import com.sz.ac.entity.AcGrpSum;
import com.sz.ac.entity.AcInvest;
import com.sz.ac.entity.AcJoinGrpLog;
import com.sz.ac.interfs.IAcGrpService;
import com.sz.ac.model.constant.AddBallEnum;
import com.sz.ac.model.constant.DefMsgException;
import com.sz.ac.model.constant.ResultData;
import com.sz.ac.model.constant.Vars;
import com.sz.ac.model.view.GrpView;
import com.sz.ac.services.mapper.ac.AcGrpMapper;
import com.sz.ac.services.mapper.ac.AcInvestMapper;
import com.sz.ac.utils.PhoneUtils;
import com.sz.ac.utils.RandomUtils;

import sun.applet.resources.MsgAppletViewer_es;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * <p>
 * 战队表 服务实现类
 * </p>
 *
 * @author ruichar
 * @since 2018-03-24
 */
@Service
public class AcGrpServiceImpl extends ServiceImpl<AcGrpMapper, AcGrp> implements IAcGrpService 
{
	private final Logger logger = LoggerFactory.getLogger(AcGrpServiceImpl.class);
	@Resource
	private AcGrpMapper grpMapper;
	@Resource
	private AcInvestMapper acInvestMapper;
	@Resource
	private TransactionTemplate transactionTemplate;
	
	public Map<String, Object> getMyGrp(String phone) 
	{
		if(StringUtils.isEmpty(phone))
		{
			throw new DefMsgException(ResultData.ERROR,"手机号不能为空");
		}
		Map<String, Object> ret = new HashMap<String, Object>();
		AcInvest param = new AcInvest();
		param.setPhone(phone);
		AcInvest invest = acInvestMapper.selectOne(param);
		
		ret.put("me", invest);
		if(invest == null || invest.getGrpId() == null){
			ret.put("myGrp", null);
			ret.put("myGrpMembers", null);
		}else{
			Integer myGrpId = invest.getGrpId();
			//成员
			Map<String, Object> columnMap = new HashMap<String, Object>();
			columnMap.put("grp_id", myGrpId);
			List<AcInvest> investMembers = acInvestMapper.selectByMap(columnMap);
			BigDecimal totalInvest = BigDecimal.ZERO;
			for(AcInvest item  : investMembers){
				item.setPhone(PhoneUtils.overPhoneNm(item.getPhone()));
				totalInvest = totalInvest.add(item.getAmount());
			}
			ret.put("myGrpMembers", investMembers);
			//队伍
			AcGrp grpParam = new AcGrp();
			grpParam.setId(myGrpId);
			AcGrp grp = grpMapper.selectOne(grpParam);
			grp.setGrpLeaderPhone(PhoneUtils.overPhoneNm(grp.getGrpLeaderPhone()));
			
			GrpView grpView = new GrpView();
			grpView.setBallNm(grp.getBallNm());
			grpView.setGrpId(grp.getId());
			grpView.setGrpLeaderPhone(grp.getGrpLeaderPhone());
			grpView.setTotalInvest(totalInvest);
			ret.put("myGrp", grpView);
		}
		
		
		return ret;
	}

	@Transactional
//	@Override
	public boolean createMyGrp(String phone) 
	{
		AcInvest param = new AcInvest();
		param.setPhone(phone);
		AcInvest invest = acInvestMapper.selectOne(param);
		boolean isNewInvest = false;
		if(invest == null || StringUtils.isEmpty(invest.getPhone()))
		{
			Date now = new Date();
			invest = new AcInvest();
			invest.setPhone(phone);
			invest.setInvestTime(now);
			invest.setPicIndex(RandomUtils.getRandomInt());
			invest.setTsp(now);
			invest.insert();
			isNewInvest = true;
		}
		if(invest.getGrpId()!=null && invest.getGrpId() >0)
		{
			throw new DefMsgException("已经加入战队，不允许创建");
		}
		AcGrp grp = new AcGrp();
		grp.setGrpLeaderPhone(phone);
		grp.setTsp(new Date());
		grp.setPicIndex(invest.getPicIndex());
		grpMapper.insert(grp);
		AcGrp paramGrp = new AcGrp();
		paramGrp.setGrpLeaderPhone(phone);
		int grpId = grpMapper.selectOne(paramGrp).getId();
		invest.setGrpId(grpId);
		invest.updateById();
		return isNewInvest;
	}

//	@Override
	public void joinGrpByInvteing(String phone,Integer inviteId ,Integer grpId ) 
	{
		AcInvest param = new AcInvest();
		param.setPhone(phone);
		AcInvest invest = acInvestMapper.selectOne(param);
		if(invest == null || StringUtils.isEmpty(invest.getPhone()))
		{
			logger.info("=========invest is not exist and save in db auto======");
			invest = new AcInvest();
			invest.setPhone(phone);
			invest.setInvestBall(0);
			invest.setPicIndex(RandomUtils.getRandomInt());
			invest.setTsp(new Date());
			invest.insert();
		}
		if(invest.getGrpId()!=null && invest.getGrpId() >0)
		{
			throw new DefMsgException("已经加入战队，不允许再次加入");
		}
		
		AcInvest investInvite = acInvestMapper.selectById(inviteId);
		if(investInvite == null || StringUtils.isEmpty(investInvite.getPhone()))
		{
			throw new DefMsgException("用户信息不存在");
		}
		 
		Map<String, Object> colomnMap = new HashMap<String, Object>();
		colomnMap.put("grp_id", grpId);
		List<AcInvest> grpInvestList = acInvestMapper.selectByMap(colomnMap);
		if(grpInvestList.size() > Vars.MAX_MEMBER_GRP)
		{
			throw new DefMsgException("战队已满员");
		}
		
		invest.setGrpId(grpId);
		invest.setTsp(new Date());
		invest.updateById();
		//存储加入日志
		AcJoinGrpLog joinLog = new AcJoinGrpLog();
		joinLog.setGrpId(grpId);
		joinLog.setInvestId(invest.getId());
		joinLog.setTsp(new Date());
		joinLog.insert();
		
	}

	public List<AcGrp> getAllGrp() {
		//排名
		List<AcGrp> grpList = grpMapper.getAllGrp();
		for(AcGrp item : grpList)
		{
			item.setGrpLeaderPhone(PhoneUtils.overPhoneNm(item.getGrpLeaderPhone()));
		}
		return grpList;
	}

	public List<GrpView> getAllGrpView() 
	{
		List<GrpView> grpViewList = new ArrayList<GrpView>();
		List<AcGrp> allGrpList = grpMapper.getAllGrp();
		for(AcGrp item : allGrpList)
		{
			GrpView view = new GrpView();
			view.setBallNm(item.getBallNm());
			view.setGrpId(item.getId());
			view.setGrpLeaderPhone(item.getGrpLeaderPhone());
			BigDecimal totalInvest = BigDecimal.ZERO;
			//获取成员
			Map<String, Object> columnMap = new HashMap<String, Object>();
			columnMap.put("grp_id", item.getId());
			List<AcInvest> investList = acInvestMapper.selectByMap(columnMap);
			for(AcInvest data : investList)
			{
				totalInvest = totalInvest.add(data.getAmount());
			}
			
			view.setTotalInvest(totalInvest);
			grpViewList.add(view);
		}
		
		return grpViewList;
	}

	@Transactional
	public void statistic() 
	{
		Date now = new Date();
		List<AcGrp> grpList = grpMapper.getAllGrp();
		int i = 1;
		for(AcGrp item : grpList)
		{
			//统计表中插入数据，同时，战队球数清零
			AcBallLog ballLog = new AcBallLog();
			if(i == 1){
				item.setBallNm(item.getBallNm()+Vars.FIRST_GOALS);
				ballLog.setBall(Vars.FIRST_GOALS);
				ballLog.setDesc(AddBallEnum.first_add.name());
				ballLog.setGrpId(item.getId());
				ballLog.setPhone(item.getGrpLeaderPhone());
				ballLog.setTsp(now);
				ballLog.insert();
			}else if(i==2){
				item.setBallNm(item.getBallNm()+Vars.SECOND_GOALS);
				ballLog.setBall(Vars.SECOND_GOALS);
				ballLog.setDesc(AddBallEnum.second_add.name());
				ballLog.setGrpId(item.getId());
				ballLog.setPhone(item.getGrpLeaderPhone());
				ballLog.setTsp(now);
				ballLog.insert();
			}else if(i==3){
				item.setBallNm(item.getBallNm()+Vars.THIRD_GOALS);
				ballLog.setBall(Vars.THIRD_GOALS);
				ballLog.setDesc(AddBallEnum.third_add.name());
				ballLog.setGrpId(item.getId());
				ballLog.setPhone(item.getGrpLeaderPhone());
				ballLog.setTsp(now);
				ballLog.insert();
			}
			//插入统计表
			AcGrpSum sum = new AcGrpSum();
			sum.setBallNmSum(item.getBallNm());
			sum.setGrpId(item.getId());
			sum.setGrpLeaderPhone(item.getGrpLeaderPhone());
			sum.setInvestNm(this.getInvestCountByGrpId(item.getId()));
			sum.setTsp(now);
			sum.insert();
			item.setBallNm(0);
			item.updateById();
			i++;
		}
		
	}
	
	
	private int getInvestCountByGrpId(int grpId)
	{
		List<AcInvest> acInvestList = acInvestMapper.selectList(new EntityWrapper<AcInvest>().where("grp_id={0}", grpId));
		return acInvestList.size();
	}
	
}
